package com.example.myapplication.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.myapplication.R;

public class BindingActivity extends AppCompatActivity {

    MyBindService myService;
    boolean iBind;
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            Log.i("onServiceConnected", "onServiceConnected: ..................");
            MyBindService.MyBinder myBinder = (MyBindService.MyBinder) iBinder;
            myService = myBinder.getService();
            iBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("onServiceDisconnected", "onServiceDisconnected: ..................");
            iBind = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binding);
    }

    public void bindService(View view) {
        Intent intent = new Intent(this,MyBindService.class);
        bindService(intent,connection, Context.BIND_AUTO_CREATE);
    }

    public void unBindService(View view) {
        if(iBind) {
            unbindService(connection);
            iBind = false;
        };
    }

    public void getData(View view) {
        if(iBind){
            Toast.makeText(this,"随机数为："+myService.getRandomNumber(),Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"服务未绑定",Toast.LENGTH_SHORT).show();

        }
    }
}